package com.jinke.api.modules.api.interceptor;

import cn.hutool.json.JSONUtil;
import com.jinke.api.common.api.CommonResult;
import com.jinke.api.modules.api.conf.ApiUrlsConfig;
import com.jinke.api.modules.api.error.ApiError;
import com.jinke.api.modules.app.service.UserApiService;
import com.jinke.api.security.util.ApiUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ApiInterceptor implements HandlerInterceptor {

    @Autowired
    private UserApiService userApiService;
    @Autowired
    private ApiUrlsConfig apiIgnoreUrlsConfig;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行
        if(apiIgnoreUrlsConfig.getUrls().contains(request.getRequestURI()) ){
            return true;
        }

        // 在请求处理之前进行拦截操作
        String apiKey = request.getHeader("Authorization"); // 替换Your-Key为你期望的消息头key
        if (apiKey == null) {
            response.setHeader("Content-Type", "application/json");
            //Authorization值为空
            response.getWriter().write(JSONUtil.toJsonStr(CommonResult.failed(ApiError.AUTHORIZATION_EMPTY)));
            return false;
        } else {
            Integer userId = isValidKey(apiKey);
            if (userId == 0) {
                response.setHeader("Content-Type", "application/json");
                response.getWriter().write(JSONUtil.toJsonStr(CommonResult.failed(ApiError.AUTHORIZATION_FAILED)));
                return false;
            }

            ApiUserUtil.setUserInfo(userId);
        }

        // 如果key合法，继续处理请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求处理之后进行拦截操作
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 完成请求后的清理操作
    }

    /**
     * 校验API密钥
     * @param apiKey
     * @return
     */
    private Integer isValidKey(String apiKey) {
        return userApiService.check(apiKey);
    }
}
